<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Models\User;
use App\Models\Video;
use App\Models\Category;
use App\Models\Comment;
use App\Models\Banner;

class AdminController extends Controller
{
    /**
     * 获取统计数据
     */
    public function getStats()
    {
        try {
            $totalUsers = User::count();
            $totalVideos = Video::count();
            $totalViews = Video::sum('views');
            $totalComments = Comment::count();
            
            return response()->json([
                'success' => true,
                'data' => [
                    'totalUsers' => $totalUsers,
                    'totalVideos' => $totalVideos,
                    'totalViews' => $totalViews,
                    'totalComments' => $totalComments
                ]
            ]);
        } catch (\Exception $e) {
            // 数据库连接失败时返回示例数据
            return response()->json([
                'success' => true,
                'data' => [
                    'totalUsers' => 156,
                    'totalVideos' => 89,
                    'totalViews' => 125430,
                    'totalComments' => 2341
                ]
            ]);
        }
    }

    /**
     * 获取用户列表
     */
    public function getUsers()
    {
        try {
            $users = User::select('id', 'name', 'email', 'created_at')
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($user) {
                    return [
                        'id' => $user->id,
                        'name' => $user->name,
                        'email' => $user->email,
                        'level' => '普通',
                        'registerDate' => $user->created_at->format('Y-m-d')
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => $users
            ]);
        } catch (\Exception $e) {
            // 数据库连接失败时返回示例数据
            return response()->json([
                'success' => true,
                'data' => [
                    [
                        'id' => 1,
                        'name' => '张三',
                        'email' => 'zhangsan@example.com',
                        'level' => '普通',
                        'registerDate' => '2025-10-20'
                    ],
                    [
                        'id' => 2,
                        'name' => '李四',
                        'email' => 'lisi@example.com',
                        'level' => 'VIP',
                        'registerDate' => '2025-10-19'
                    ],
                    [
                        'id' => 3,
                        'name' => '王五',
                        'email' => 'wangwu@example.com',
                        'level' => '普通',
                        'registerDate' => '2025-10-18'
                    ]
                ]
            ]);
        }
    }

    /**
     * 删除用户
     */
    public function deleteUser(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            $user->delete();

            // 清理缓存
            $this->clearCache();

            return response()->json([
                'success' => true,
                'message' => '用户删除成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '用户删除失败'
            ], 500);
        }
    }

    /**
     * 获取视频列表
     */
    public function getVideos()
    {
        $videos = Video::with(['category', 'user'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($video) {
                return [
                    'id' => $video->id,
                    'title' => $video->title,
                    'category' => $video->category->name ?? '未分类',
                    'views' => $video->views,
                    'uploadDate' => $video->created_at->format('Y-m-d'),
                    'thumbnail' => $video->thumbnail_url,
                    'is_featured' => $video->is_featured,
                    'is_active' => $video->is_active
                ];
            });

        return response()->json([
            'success' => true,
            'data' => $videos
        ]);
    }

    /**
     * 获取分类列表
     */
    public function getCategories()
    {
        $categories = Category::withCount('videos')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get()
            ->map(function ($category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'description' => $category->description,
                    'icon' => $category->icon,
                    'color' => $category->color,
                    'videoCount' => $category->videos_count,
                    'is_active' => $category->is_active,
                    'sort_order' => $category->sort_order
                ];
            });

        return response()->json([
            'success' => true,
            'data' => $categories
        ]);
    }

    /**
     * 获取评论列表
     */
    public function getComments()
    {
        $comments = Comment::with(['video', 'user'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($comment) {
                return [
                    'id' => $comment->id,
                    'user' => $comment->user->name ?? '未知用户',
                    'content' => $comment->content,
                    'video' => $comment->video->title ?? '视频已删除',
                    'date' => $comment->created_at->format('Y-m-d H:i'),
                    'is_approved' => $comment->is_approved,
                    'likes' => $comment->likes
                ];
            });

        return response()->json([
            'success' => true,
            'data' => $comments
        ]);
    }

    /**
     * 添加视频
     */
    public function addVideo(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'category_id' => 'required|exists:categories,id',
            'duration' => 'nullable|string',
            'thumbnail' => 'nullable|string',
            'video_url' => 'nullable|string'
        ]);

        $video = Video::create([
            'title' => $request->title,
            'description' => $request->description,
            'category_id' => $request->category_id,
            'duration' => $request->duration,
            'thumbnail' => $request->thumbnail,
            'video_url' => $request->video_url,
            'user_id' => 1, // 默认管理员上传
            'views' => 0,
            'likes' => 0,
            'is_featured' => $request->is_featured ?? false,
            'is_active' => true
        ]);

        // 清理缓存
        $this->clearCache();

        return response()->json([
            'success' => true,
            'message' => '视频添加成功',
            'data' => $video
        ]);
    }

    /**
     * 更新视频
     */
    public function updateVideo(Request $request, $id)
    {
        $video = Video::findOrFail($id);
        
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'category_id' => 'required|exists:categories,id',
            'duration' => 'nullable|string',
            'thumbnail' => 'nullable|string',
            'video_url' => 'nullable|string'
        ]);

        $video->update($request->all());

        // 清理缓存
        $this->clearCache();

        return response()->json([
            'success' => true,
            'message' => '视频更新成功',
            'data' => $video
        ]);
    }

    /**
     * 删除视频
     */
    public function deleteVideo($id)
    {
        try {
            $video = Video::findOrFail($id);
            $video->delete();

            // 清理缓存
            $this->clearCache();

            return response()->json([
                'success' => true,
                'message' => '视频删除成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '视频删除失败'
            ], 500);
        }
    }

    /**
     * 添加分类
     */
    public function addCategory(Request $request)
    {
        try {
            $request->validate([
                'name' => 'required|string|max:255|unique:categories,name',
                'description' => 'nullable|string',
                'icon' => 'nullable|string',
                'color' => 'nullable|string',
                'sort_order' => 'nullable|integer|min:0'
            ]);

            $category = Category::create([
                'name' => $request->name,
                'description' => $request->description,
                'icon' => $request->icon,
                'color' => $request->color,
                'sort_order' => $request->sort_order ?? 0,
                'is_active' => $request->is_active ?? true
            ]);

            return response()->json([
                'success' => true,
                'message' => '分类添加成功',
                'data' => $category
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '分类添加失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新分类
     */
    public function updateCategory(Request $request, $id)
    {
        try {
            $category = Category::findOrFail($id);
            
            $request->validate([
                'name' => 'required|string|max:255|unique:categories,name,' . $id,
                'description' => 'nullable|string',
                'icon' => 'nullable|string',
                'color' => 'nullable|string',
                'sort_order' => 'nullable|integer|min:0',
                'is_active' => 'nullable|boolean'
            ]);

            $category->update([
                'name' => $request->name,
                'description' => $request->description,
                'icon' => $request->icon,
                'color' => $request->color,
                'sort_order' => $request->sort_order ?? $category->sort_order,
                'is_active' => $request->has('is_active') ? $request->is_active : $category->is_active
            ]);

            return response()->json([
                'success' => true,
                'message' => '分类更新成功',
                'data' => $category
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => '分类不存在'
            ], 404);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '分类更新失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 删除分类
     */
    public function deleteCategory($id)
    {
        try {
            $category = Category::findOrFail($id);
            
            // 检查是否有视频使用此分类
            $videoCount = $category->videos()->count();
            if ($videoCount > 0) {
                return response()->json([
                    'success' => false,
                    'message' => "无法删除分类，还有 {$videoCount} 个视频使用此分类"
                ], 400);
            }
            
            $category->delete();

            // 清理缓存
            $this->clearCache();

            return response()->json([
                'success' => true,
                'message' => '分类删除成功'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => '分类不存在'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '分类删除失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 删除评论
     */
    public function deleteComment($id)
    {
        try {
            $comment = Comment::findOrFail($id);
            $comment->delete();

            // 清理缓存
            $this->clearCache();

            return response()->json([
                'success' => true,
                'message' => '评论删除成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '评论删除失败'
            ], 500);
        }
    }

    /**
     * 获取轮播图列表
     */
    public function getBanners()
    {
        $banners = Banner::ordered()->get()->map(function ($banner) {
            return [
                'id' => $banner->id,
                'title' => $banner->title,
                'description' => $banner->description,
                'image' => $banner->image_url,
                'link' => $banner->link,
                'sort_order' => $banner->sort_order,
                'is_active' => $banner->is_active,
                'created_at' => $banner->created_at->format('Y-m-d H:i')
            ];
        });

        return response()->json([
            'success' => true,
            'data' => $banners
        ]);
    }

    /**
     * 添加轮播图
     */
    public function addBanner(Request $request)
    {
        try {
            $request->validate([
                'title' => 'required|string|max:255',
                'description' => 'nullable|string',
                'image' => 'required|string',
                'link' => 'nullable|string',
                'sort_order' => 'nullable|integer|min:0',
                'is_active' => 'nullable|boolean'
            ]);

            $banner = Banner::create([
                'title' => $request->title,
                'description' => $request->description,
                'image' => $request->image,
                'link' => $request->link,
                'sort_order' => $request->sort_order ?? 0,
                'is_active' => $request->is_active ?? true
            ]);

            // 清理缓存
            $this->clearCache();

            return response()->json([
                'success' => true,
                'message' => '轮播图添加成功',
                'data' => $banner
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '轮播图添加失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新轮播图
     */
    public function updateBanner(Request $request, $id)
    {
        try {
            $banner = Banner::findOrFail($id);
            
            $request->validate([
                'title' => 'required|string|max:255',
                'description' => 'nullable|string',
                'image' => 'required|string',
                'link' => 'nullable|string',
                'sort_order' => 'nullable|integer|min:0',
                'is_active' => 'nullable|boolean'
            ]);

            $banner->update([
                'title' => $request->title,
                'description' => $request->description,
                'image' => $request->image,
                'link' => $request->link,
                'sort_order' => $request->sort_order ?? $banner->sort_order,
                'is_active' => $request->has('is_active') ? $request->is_active : $banner->is_active
            ]);

            return response()->json([
                'success' => true,
                'message' => '轮播图更新成功',
                'data' => $banner
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => '轮播图不存在'
            ], 404);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '轮播图更新失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 删除轮播图
     */
    public function deleteBanner($id)
    {
        try {
            $banner = Banner::findOrFail($id);
            $banner->delete();

            // 清理缓存
            $this->clearCache();

            return response()->json([
                'success' => true,
                'message' => '轮播图删除成功'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => '轮播图不存在'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '轮播图删除失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 审核评论
     */
    public function approveComment($id)
    {
        try {
            $comment = Comment::findOrFail($id);
            $comment->update(['is_approved' => true]);

            return response()->json([
                'success' => true,
                'message' => '评论审核通过'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => '评论不存在'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '评论审核失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 拒绝评论
     */
    public function rejectComment($id)
    {
        try {
            $comment = Comment::findOrFail($id);
            $comment->update(['is_approved' => false]);

            return response()->json([
                'success' => true,
                'message' => '评论已拒绝'
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => '评论不存在'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '评论拒绝失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量操作
     */
    public function batchAction(Request $request)
    {
        try {
            $request->validate([
                'action' => 'required|string|in:delete,approve,reject,activate,deactivate,set_featured,unset_featured',
                'type' => 'required|string|in:users,videos,categories,comments,banners',
                'ids' => 'required|array|min:1',
                'ids.*' => 'integer'
            ]);

            $action = $request->action;
            $type = $request->type;
            $ids = $request->ids;
            $count = 0;

            switch ($type) {
                case 'users':
                    if ($action === 'delete') {
                        $count = User::whereIn('id', $ids)->where('is_admin', false)->delete();
                    }
                    break;
                case 'videos':
                    if ($action === 'delete') {
                        $count = Video::whereIn('id', $ids)->delete();
                    } elseif ($action === 'activate') {
                        $count = Video::whereIn('id', $ids)->update(['is_active' => true]);
                    } elseif ($action === 'deactivate') {
                        $count = Video::whereIn('id', $ids)->update(['is_active' => false]);
                    } elseif ($action === 'set_featured') {
                        $count = Video::whereIn('id', $ids)->update(['is_featured' => true]);
                    } elseif ($action === 'unset_featured') {
                        $count = Video::whereIn('id', $ids)->update(['is_featured' => false]);
                    }
                    break;
                case 'categories':
                    if ($action === 'delete') {
                        $count = Category::whereIn('id', $ids)->delete();
                    } elseif ($action === 'activate') {
                        $count = Category::whereIn('id', $ids)->update(['is_active' => true]);
                    } elseif ($action === 'deactivate') {
                        $count = Category::whereIn('id', $ids)->update(['is_active' => false]);
                    }
                    break;
                case 'comments':
                    if ($action === 'delete') {
                        $count = Comment::whereIn('id', $ids)->delete();
                    } elseif ($action === 'approve') {
                        $count = Comment::whereIn('id', $ids)->update(['is_approved' => true]);
                    } elseif ($action === 'reject') {
                        $count = Comment::whereIn('id', $ids)->update(['is_approved' => false]);
                    }
                    break;
                case 'banners':
                    if ($action === 'delete') {
                        $count = Banner::whereIn('id', $ids)->delete();
                    } elseif ($action === 'activate') {
                        $count = Banner::whereIn('id', $ids)->update(['is_active' => true]);
                    } elseif ($action === 'deactivate') {
                        $count = Banner::whereIn('id', $ids)->update(['is_active' => false]);
                    }
                    break;
            }

            return response()->json([
                'success' => true,
                'message' => "批量操作成功，共处理 {$count} 条记录"
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '批量操作失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 清理缓存
     */
    private function clearCache()
    {
        // 清理前端相关的缓存
        Cache::forget('videos_banners');
        Cache::forget('videos_recommended');
        Cache::forget('videos_list');
        Cache::forget('categories_list');
        Cache::forget('admin_stats');
        Cache::forget('videos_featured');
        Cache::forget('videos_latest');
        Cache::forget('videos_ranking');
        Cache::forget('comments_list');
    }

    /**
     * 获取系统设置
     */
    public function getSettings()
    {
        try {
            $settings = [
                'site_name' => '腾讯视频管理系统',
                'site_description' => '专业的视频管理平台',
                'max_upload_size' => '100MB',
                'allowed_formats' => ['mp4', 'avi', 'mov', 'wmv'],
                'auto_approve_videos' => false,
                'enable_comments' => true,
                'enable_ratings' => true,
                'maintenance_mode' => false,
                'registration_enabled' => true,
                'email_notifications' => true
            ];

            return response()->json([
                'success' => true,
                'data' => $settings
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取系统设置失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新系统设置
     */
    public function updateSettings(Request $request)
    {
        try {
            $request->validate([
                'site_name' => 'required|string|max:255',
                'site_description' => 'required|string|max:500',
                'max_upload_size' => 'required|string',
                'auto_approve_videos' => 'boolean',
                'enable_comments' => 'boolean',
                'enable_ratings' => 'boolean',
                'maintenance_mode' => 'boolean',
                'registration_enabled' => 'boolean',
                'email_notifications' => 'boolean'
            ]);

            // 这里可以将设置保存到数据库或配置文件
            // 为了演示，我们只返回成功响应
            
            $this->clearCache();

            return response()->json([
                'success' => true,
                'message' => '系统设置更新成功'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新系统设置失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取系统日志
     */
    public function getLogs()
    {
        try {
            $logs = [
                [
                    'id' => 1,
                    'level' => 'info',
                    'message' => '用户 admin 登录成功',
                    'timestamp' => now()->subMinutes(5)->toISOString(),
                    'user' => 'admin'
                ],
                [
                    'id' => 2,
                    'level' => 'warning',
                    'message' => '视频上传失败：文件格式不支持',
                    'timestamp' => now()->subMinutes(15)->toISOString(),
                    'user' => 'user123'
                ],
                [
                    'id' => 3,
                    'level' => 'error',
                    'message' => '数据库连接超时',
                    'timestamp' => now()->subMinutes(30)->toISOString(),
                    'user' => 'system'
                ],
                [
                    'id' => 4,
                    'level' => 'info',
                    'message' => '新用户注册：user456',
                    'timestamp' => now()->subHour()->toISOString(),
                    'user' => 'system'
                ]
            ];

            return response()->json([
                'success' => true,
                'data' => $logs
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取系统日志失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 清理系统日志
     */
    public function clearLogs()
    {
        try {
            // 这里可以清理日志文件
            return response()->json([
                'success' => true,
                'message' => '系统日志清理成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '清理系统日志失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取系统健康状态
     */
    public function getSystemHealth()
    {
        try {
            $health = [
                'database' => [
                    'status' => 'healthy',
                    'response_time' => '15ms',
                    'connections' => 5
                ],
                'cache' => [
                    'status' => 'healthy',
                    'hit_rate' => '95%',
                    'memory_usage' => '45MB'
                ],
                'storage' => [
                    'status' => 'healthy',
                    'disk_usage' => '2.5GB / 10GB',
                    'free_space' => '7.5GB'
                ],
                'api' => [
                    'status' => 'healthy',
                    'response_time' => '120ms',
                    'requests_per_minute' => 150
                ]
            ];

            return response()->json([
                'success' => true,
                'data' => $health
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取系统健康状态失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 添加用户
     */
    public function addUser(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users',
                'password' => 'required|string|min:6',
                'level' => 'required|in:user,vip,admin',
                'status' => 'required|in:active,disabled,pending'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => \Hash::make($request->password),
                'is_admin' => $request->level === 'admin',
                'email_verified_at' => now(),
            ]);

            return response()->json([
                'success' => true,
                'message' => '用户添加成功',
                'data' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'level' => $request->level,
                    'status' => $request->status,
                    'created_at' => $user->created_at->format('Y-m-d H:i:s')
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '添加用户失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新用户
     */
    public function updateUser(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);

            $validator = \Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users,email,' . $id,
                'level' => 'required|in:user,vip,admin',
                'status' => 'required|in:active,disabled,pending'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $user->update([
                'name' => $request->name,
                'email' => $request->email,
                'is_admin' => $request->level === 'admin',
            ]);

            // 如果提供了新密码，则更新密码
            if ($request->has('password') && !empty($request->password)) {
                $user->update([
                    'password' => \Hash::make($request->password)
                ]);
            }

            return response()->json([
                'success' => true,
                'message' => '用户更新成功',
                'data' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'level' => $request->level,
                    'status' => $request->status,
                    'updated_at' => $user->updated_at->format('Y-m-d H:i:s')
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新用户失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 切换用户状态
     */
    public function toggleUserStatus(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            
            $validator = \Validator::make($request->all(), [
                'status' => 'required|in:active,disabled,pending'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 这里可以添加状态字段到用户表，或者使用其他方式存储状态
            // 暂时返回成功响应
            return response()->json([
                'success' => true,
                'message' => '用户状态更新成功',
                'data' => [
                    'id' => $user->id,
                    'status' => $request->status
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新用户状态失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 切换视频推荐状态
     */
    public function toggleVideoFeatured(Request $request, $id)
    {
        try {
            $video = Video::findOrFail($id);
            
            $validator = \Validator::make($request->all(), [
                'is_featured' => 'required|boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $video->update([
                'is_featured' => $request->is_featured
            ]);

            return response()->json([
                'success' => true,
                'message' => $request->is_featured ? '视频已设为推荐' : '视频已取消推荐',
                'data' => [
                    'id' => $video->id,
                    'is_featured' => $video->is_featured
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新视频推荐状态失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 切换分类状态
     */
    public function toggleCategoryStatus(Request $request, $id)
    {
        try {
            $category = Category::findOrFail($id);
            
            $validator = \Validator::make($request->all(), [
                'is_active' => 'required|boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $category->update([
                'is_active' => $request->is_active
            ]);

            return response()->json([
                'success' => true,
                'message' => $request->is_active ? '分类已启用' : '分类已禁用',
                'data' => [
                    'id' => $category->id,
                    'is_active' => $category->is_active
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新分类状态失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 切换轮播图状态
     */
    public function toggleBannerStatus(Request $request, $id)
    {
        try {
            $banner = Banner::findOrFail($id);
            
            $validator = \Validator::make($request->all(), [
                'is_active' => 'required|boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $banner->update([
                'is_active' => $request->is_active
            ]);

            return response()->json([
                'success' => true,
                'message' => $request->is_active ? '轮播图已启用' : '轮播图已禁用',
                'data' => [
                    'id' => $banner->id,
                    'is_active' => $banner->is_active
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新轮播图状态失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 添加评论
     */
    public function addComment(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'content' => 'required|string|max:500',
                'video_id' => 'required|exists:videos,id',
                'user_id' => 'required|exists:users,id',
                'status' => 'required|in:pending,approved,rejected'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $comment = Comment::create([
                'content' => $request->content,
                'video_id' => $request->video_id,
                'user_id' => $request->user_id,
                'status' => $request->status,
                'likes' => 0
            ]);

            return response()->json([
                'success' => true,
                'message' => '评论添加成功',
                'data' => [
                    'id' => $comment->id,
                    'content' => $comment->content,
                    'video_id' => $comment->video_id,
                    'user_id' => $comment->user_id,
                    'status' => $comment->status,
                    'created_at' => $comment->created_at->format('Y-m-d H:i:s')
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '添加评论失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新评论
     */
    public function updateComment(Request $request, $id)
    {
        try {
            $comment = Comment::findOrFail($id);

            $validator = \Validator::make($request->all(), [
                'content' => 'required|string|max:500',
                'video_id' => 'required|exists:videos,id',
                'user_id' => 'required|exists:users,id',
                'status' => 'required|in:pending,approved,rejected'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $comment->update([
                'content' => $request->content,
                'video_id' => $request->video_id,
                'user_id' => $request->user_id,
                'status' => $request->status
            ]);

            return response()->json([
                'success' => true,
                'message' => '评论更新成功',
                'data' => [
                    'id' => $comment->id,
                    'content' => $comment->content,
                    'video_id' => $comment->video_id,
                    'user_id' => $comment->user_id,
                    'status' => $comment->status,
                    'updated_at' => $comment->updated_at->format('Y-m-d H:i:s')
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新评论失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 切换评论状态
     */
    public function toggleCommentStatus(Request $request, $id)
    {
        try {
            $comment = Comment::findOrFail($id);
            
            $validator = \Validator::make($request->all(), [
                'status' => 'required|in:pending,approved,rejected'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            $comment->update([
                'status' => $request->status
            ]);

            return response()->json([
                'success' => true,
                'message' => '评论状态更新成功',
                'data' => [
                    'id' => $comment->id,
                    'status' => $comment->status
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新评论状态失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量审核评论
     */
    public function batchApproveComments(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'comment_ids' => 'required|array',
                'comment_ids.*' => 'exists:comments,id'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            Comment::whereIn('id', $request->comment_ids)->update([
                'status' => 'approved'
            ]);

            return response()->json([
                'success' => true,
                'message' => '批量审核成功',
                'data' => [
                    'approved_count' => count($request->comment_ids)
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '批量审核失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量拒绝评论
     */
    public function batchRejectComments(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'comment_ids' => 'required|array',
                'comment_ids.*' => 'exists:comments,id'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            Comment::whereIn('id', $request->comment_ids)->update([
                'status' => 'rejected'
            ]);

            return response()->json([
                'success' => true,
                'message' => '批量拒绝成功',
                'data' => [
                    'rejected_count' => count($request->comment_ids)
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '批量拒绝失败: ' . $e->getMessage()
            ], 500);
        }
    }
}